const { PrismaClient } = require('@prisma/client');
const fs = require('fs');
const { parse } = require('csv-parse');
const { parse: parseDate } = require('date-fns');
const { hash } = require('bcryptjs');

const prisma = new PrismaClient();

// 添加 User 和 SavedTrip 的类型定义
interface UserCSV {
  id: string;
  username: string;
  password: string;
  email: string | null;
  name: string | null;
  createdAt: string;
  updatedAt: string;
}

interface SavedTripCSV {
  id: string;
  createdAt: string;
  userId: string;
  tripId: string;
}

// 添加 Trip 的类型定义
interface TripCSV {
  id: string;
  title: string;
  startDate: string;
  endDate: string;
  userId: string;
  isPublic: string;
  shareCode: string | null;
  createdAt: string;
  updatedAt: string;
  isOfficial: string;
  description: string | null;
  imageUrl: string | null;
}

// 定义 CSV 数据的类型
interface DestinationCSV {
  id: string;
  name: string;
  description: string | null;
  imageUrl: string | null;
  createdAt: string;
  updatedAt: string;
  createdById: string | null;
  isOfficial: string;
  metadata: string;
}

interface ActivityCSV {
  id: string;
  title: string;
  date: string;
  description: string | null;
  tripId: string | null;
  destinationId: string | null;
  createdAt: string;
  updatedAt: string;
  metadata: string | null;
}

function parseCustomDate(dateStr: string): Date {
  try {
    // 尝试解析 "dd/MM/yyyy HH:mm:ss.SSS" 格式
    if (dateStr.includes('/') && dateStr.includes(':')) {
      const [datePart, timePart] = dateStr.split(' ');
      const [day, month, year] = datePart.split('/').map(Number);
      const [hours, minutes, seconds] = timePart.split(':').map(Number);
      return new Date(year, month - 1, day, hours, minutes, seconds);
    }
    
    // 尝试解析 "dd/MM/yyyy" 格式
    if (dateStr.includes('/')) {
      const [day, month, year] = dateStr.split('/').map(Number);
      return new Date(year, month - 1, day);
    }
    
    // 如果都不匹配，尝试 ISO 格式
    return new Date(dateStr);
  } catch (error) {
    console.error(`Error parsing date: ${dateStr}`, error);
    // 返回当前日期作为后备
    return new Date();
  }
}

// 添加一个辅助函数来验证日期是否有效
function isValidDate(date: Date): boolean {
  return date instanceof Date && !isNaN(date.getTime());
}

async function importData() {
  // 导入用户数据
  const userData = fs.readFileSync('User.csv', 'utf-8');
  const users: UserCSV[] = await new Promise((resolve, reject) => {
    parse(userData, {
      columns: true,
      skip_empty_lines: true,
    }, (err: Error | null, data: UserCSV[]) => {
      if (err) reject(err);
      resolve(data);
    });
  });

  // 导入用户
  for (const user of users) {
    try {
      await prisma.user.create({
        data: {
          id: user.id,
          username: user.username,
          password: user.password, // 已经是哈希过的密码
          email: user.email,
          name: user.name,
          createdAt: parseCustomDate(user.createdAt),
          updatedAt: parseCustomDate(user.updatedAt),
        },
      });
      console.log(`Imported user: ${user.username}`);
    } catch (error) {
      console.error(`Error importing user ${user.username}:`, error);
    }
  }

  // 导入 Trip 数据
  const tripData = fs.readFileSync('Trip.csv', 'utf-8');
  const trips: TripCSV[] = await new Promise((resolve, reject) => {
    parse(tripData, {
      columns: true,
      skip_empty_lines: true,
    }, (err: Error | null, data: TripCSV[]) => {
      if (err) reject(err);
      resolve(data);
    });
  });

  // 导入 Destination 数据
  const destinationData = fs.readFileSync('Destination.csv', 'utf-8');
  const destinations: DestinationCSV[] = await new Promise((resolve, reject) => {
    parse(destinationData, {
      columns: true,
      skip_empty_lines: true,
    }, (err: Error | null, data: DestinationCSV[]) => {
      if (err) reject(err);
      resolve(data);
    });
  });

  // 导入 Activity 数据
  const activityData = fs.readFileSync('Activity.csv', 'utf-8');
  const activities: ActivityCSV[] = await new Promise((resolve, reject) => {
    parse(activityData, {
      columns: true,
      skip_empty_lines: true,
    }, (err: Error | null, data: ActivityCSV[]) => {
      if (err) reject(err);
      resolve(data);
    });
  });

  console.log(`Found ${trips.length} trips, ${destinations.length} destinations and ${activities.length} activities`);

  // 先导入行程
  for (const trip of trips) {
    try {
      const tripData = {
        id: trip.id,
        title: trip.title,
        startDate: parseCustomDate(trip.startDate),
        endDate: parseCustomDate(trip.endDate),
        userId: trip.userId,
        isPublic: trip.isPublic === '1',
        shareCode: trip.shareCode || null,
        createdAt: parseCustomDate(trip.createdAt),
        updatedAt: parseCustomDate(trip.updatedAt),
        isOfficial: trip.isOfficial === '1',
        description: trip.description,
        imageUrl: trip.imageUrl || null,
      };

      console.log('Creating trip with data:', tripData);

      await prisma.trip.create({
        data: tripData
      });
      console.log(`Imported trip: ${trip.title}`);
    } catch (error) {
      console.error(`Error importing trip ${trip.title}:`, error);
      console.error('Trip data:', trip);
    }
  }

  // 先导入目的地
  for (const destination of destinations) {
    try {
      await prisma.destination.create({
        data: {
          id: destination.id,
          name: destination.name,
          description: destination.description,
          imageUrl: destination.imageUrl,
          createdAt: parseCustomDate(destination.createdAt),
          updatedAt: parseCustomDate(destination.updatedAt),
          createdById: destination.createdById,
          isOfficial: destination.isOfficial === '1',
          metadata: destination.metadata ? JSON.parse(destination.metadata) : null,
        },
      });
      console.log(`Imported destination: ${destination.name}`);
    } catch (error) {
      console.error(`Error importing destination ${destination.name}:`, error);
    }
  }

  // 然后导入活动，但先检查关联的 Trip 是否存在
  for (const activity of activities) {
    try {
      if (activity.tripId) {
        // 检查 Trip 是否存在
        const tripExists = await prisma.trip.findUnique({
          where: { id: activity.tripId }
        });
        if (!tripExists) {
          console.log(`Skipped activity ${activity.title} because trip ${activity.tripId} does not exist`);
          continue;
        }

        const date = parseCustomDate(activity.date);
        const createdAt = parseCustomDate(activity.createdAt);
        const updatedAt = parseCustomDate(activity.updatedAt);

        if (!isValidDate(date)) {
          throw new Error(`Invalid date: ${activity.date}`);
        }

        await prisma.activity.create({
          data: {
            id: activity.id,
            title: activity.title,
            date,
            description: activity.description,
            tripId: activity.tripId,
            destinationId: activity.destinationId || undefined,
            createdAt,
            updatedAt,
            metadata: activity.metadata ? JSON.parse(activity.metadata) : null,
          },
        });
        console.log(`Imported activity: ${activity.title}`);
      } else {
        console.log(`Skipped activity ${activity.title} due to missing tripId`);
      }
    } catch (error) {
      console.error(`Error importing activity ${activity.title}:`, error);
      console.error('Activity data:', {
        tripId: activity.tripId,
        date: activity.date,
        parsedDate: parseCustomDate(activity.date),
        createdAt: activity.createdAt,
        updatedAt: activity.updatedAt
      });
    }
  }

  // 导入收藏的行程数据
  const savedTripData = fs.readFileSync('SavedTrip.csv', 'utf-8');
  const savedTrips: SavedTripCSV[] = await new Promise((resolve, reject) => {
    parse(savedTripData, {
      columns: true,
      skip_empty_lines: true,
    }, (err: Error | null, data: SavedTripCSV[]) => {
      if (err) reject(err);
      resolve(data);
    });
  });

  // 导入收藏的行程
  for (const savedTrip of savedTrips) {
    try {
      await prisma.savedTrip.create({
        data: {
          id: savedTrip.id,
          createdAt: parseCustomDate(savedTrip.createdAt),
          userId: savedTrip.userId,
          tripId: savedTrip.tripId,
        },
      });
      console.log(`Imported saved trip: ${savedTrip.id}`);
    } catch (error) {
      console.error(`Error importing saved trip ${savedTrip.id}:`, error);
    }
  }

  console.log('Import completed');
}

importData()
  .catch(console.error)
  .finally(async () => {
    await prisma.$disconnect();
  });